<?php
namespace Controllers;

require_once('Base.php');
require_once('\Views\PageView.php');
require_once('\Views\LoginView.php');
require_once('\Views\ManageAlbumsView.php');
require_once('\Controllers\LoginController.php');
require_once('\Common\Settings.php');
require_once('\Models\LoginModel.php');
require_once('\Models\Database.php');
require_once('\Models\ManageAlbumsModel.php');
require_once('\Models\AlbumCatalog.php');
require_once('\Models\UserCatalog.php');
require_once('\Models\FileUpload.php');
require_once('\Models\Image.php');
require_once('\Models\ImageCatalog.php');

class ManageAlbumsController
{
	private $_db;
	private $_pv;
	private $_mav;
	private $_lm;
	private $_mam;
	private $_ac;
	private $_ic;
	private $_lc;
	
	public function __construct()
	{
		$this->_db 	= new \Models\Database();
		$this->_pv 	= new \Views\PageView();
		$this->_mav = new \Views\ManageAlbumsView();
		$this->_lm 	= new \Models\LoginModel();
		$this->_mam = new \Models\ManageAlbumsModel($this->_db);
		$this->_ac 	= new \Models\AlbumCatalog();
		$this->_ic 	= new \Models\ImageCatalog();
		$this->_lc 	= new \Controllers\LoginController();
	}
	
	public function createControl()
	{	
		$html = $this->_lc->createControl($this->_db, new \Views\LoginView());
		
		// Databasuppkopplingsfel om false
		if(!$html)
		{
			$html .= $this->_pv->setStatusText(\Common\Strings::DB_CONNECTION_ERROR, false);
			return $this->_pv->generateHTMLPage(\Common\Strings::TITLE_CREATE_ALBUM, $html);
		}
		
		if($this->_lm->IsLoggedIn())
		{
			$html .= $this->_pv->getMenu();
						
		 	// Om användaren vill skapa nytt album
			if($this->_mav->isCreatingAlbum())
				$html .= $this->createAlbum();
			
			// Om användaren vill lista album
		 	if($this->_mav->isListingAlbums())
				$html .= $this->listAlbums();
			
			// Om användaren vill editera album
		 	if($this->_mav->isEditingAlbum())
				$html .= $this->editAlbum();
			
		}
		$this->_db->Close();
		
		return $this->_pv->generateHTMLPage(\Common\Strings::TITLE_CREATE_ALBUM, $html);
	}
	
	private function createAlbum()
	{
		// Sätt rubrik
		$html = $this->_pv->encapsulateString("h2", \Common\Strings::HEADER_CREATE_ALBUM);
		
		// Om användaren försökt skapa ett nytt album
		if($this->_pv->valueIsSet($this->_mav->tryCreateAlbum))
		{
			// Skapa albumet och spara id
			$albumId = $this->_mam->createAlbum(
			$this->_lm->getUserId(), 
			$this->_pv->getValue($this->_pv->albumTitle), 
			$this->_pv->getValue($this->_pv->albumYear), 
			$this->_pv->getValue($this->_pv->albumDescription));
			
			// Om fel uppstod
			if(count($this->_mam->errors)>0)
				$html .= $this->_pv->printErrors($this->_mam->errors);
			else
				$this->_pv->updatePage(array($this->_pv->controller, $this->_pv->albumId), 
				array($this->_pv->editAlbum, $albumId));
		}

		$html .= $this->_mav->createAlbumForm();
		
		return $html;
	}
	
	private function listAlbums()
	{
		// Sätt rubrik
		$html = $this->_pv->encapsulateString("h1", \Common\Strings::HEADER_LIST_ALBUM);
		
		// Om användaren försökt ta bort ett album (redigeras till denna sida)
		if($this->_pv->valueIsSet($this->_mav->tryDeleteAlbum))
		{
			// Hämta album id
			$albumId = $this->_mav->getAlbumIdToDelete();
			
			if($albumId != false)
			{
				// Ta bort album
				if($this->_mam->deleteAlbum($albumId))
					$html .= $this->_pv->setStatusText(\Common\Strings::DB_ALBUM_DELETED, true);
				else
					$html .= $this->_pv->setStatusText(\Common\Strings::DB_ALBUM_DELETE_FAIL, false);
			}
			else
				$html .= $this->_pv->setStatusText(\Common\Strings::DB_ALBUM_DELETE_FAIL, false);	
		}
		
		// Hämtar användaren
		$uc = new \Models\UserCatalog();
		$userId = $this->_lm->getUserId();
		$user = $uc->getUser($this->_db, $userId);
		
		// Listar alla album om admin annars bara egna album
		if($user->isAdmin())
			$allAlbums = $this->_ac->getAlbums($this->_db);
		else
			$allAlbums = $this->_ac->getAlbums($this->_db, $userId);
		
		// Om arrayen är av fel klass
		if (get_class($allAlbums) != "Models\AlbumArray")
		{
			$html .= $this->_pv->setStatusText(\Common\Strings::DB_RETURN_TYPE_ERROR, false);
			return $this->_pv->generateHTMLPage(\Common\Strings::TITLE_CREATE_ALBUM, $html);
		}
		
		$albumsHtml = $this->_mav->getAlbumsList($allAlbums);
		
		if($albumsHtml == "")
			$html .= $this->_pv->encapsulateString("p", \Common\Strings::DB_ALBUMS_MISSING);
		else
			$html .= $albumsHtml;
		
		return $html;
	}
	
	private function editAlbum()
	{
		// Sätt rubrik
		$html = $this->_pv->encapsulateString("h1", \Common\Strings::HEADER_EDIT_ALBUM);
		
		// Hämtar id och album
		$albumId = $this->_pv->getNumericValue($this->_pv->albumId, false);
		$album = $this->_ac->getAlbum($this->_db, $albumId);
		
		// Avbryt rendering om inget album finns kopplat till id:t
		if($album == null)
			return $html . $this->_pv->setStatusText(\Common\Strings::DB_ALBUM_MISSING, false);
		
		//$_SESSION["albumId"] = $albumId; 
		
		$uc = new \Models\UserCatalog();
		$user = $uc->getUser($this->_db, $this->_lm->getUserId());
		
		// Avbryt rendering om inte den inloggade användaren är ägaren eller admin
		if($this->_lm->getUserId() != $album->UserId()) //&& $user->isAdmin() != true)
			return $html . $this->_pv->setStatusText(\Common\Strings::DB_ALBUM_OWNERNERSHIP_FAIL, false);
		
		// Länk till galleriet
		$html .= $this->_mav->getGalleryLink($albumId);
		
		// Uppdatera albumet
		if($this->_pv->valueIsSet($this->_mav->tryUpdateAlbum))
		{
			// Skapar nytt uppdaterat album
			$updatedAlbum = new \Models\Album(
			$album->AlbumId(),
			$album->UserId(), 
			$this->_pv->getValue($this->_pv->albumTitle),
			$this->_pv->getValue($this->_pv->albumYear),
			$this->_pv->getValue($this->_pv->albumDescription));
				
			if($this->_mam->updateAlbum($updatedAlbum))
				$this->_pv->updatePage(array($this->_pv->controller, $this->_pv->status, $this->_pv->albumId), 
				array($this->_pv->editAlbum, $this->_mav->albumUpdated, $albumId));
			else
				$html .= $this->_pv->printErrors($this->_mam->errors);
		}
		
		// Uppdatera albumets bilder
		if($this->_pv->valueIsSet($this->_mav->tryUpdateAlbumImages))
		{	
			// Lagra bilder som ska uppdateras	
			$images = $this->_ic->getImages($this->_db, $albumId);
			$updatedImages = new \Models\ImageArray();
			
			foreach ($images->get() as $image)
			{
				$descriptionId = $this->_pv->imageDescription."_".$image->ImageId();
				
				// name-attributet på formulär-taggen
				if($this->_pv->valueIsSet($descriptionId))
				{
					$updatedImage = new \Models\Image(
					$image->ImageId(), 
					$image->AlbumId(), 
					$this->_pv->getValue($descriptionId), 
					$image->ImageUrl(), 
					$image->ThumbUrl());
					
					$updatedImages->add($updatedImage);
				}
			}
			
			// Lagra bilder som ska tas bort
			$imagesToDelete = array();
			
			foreach ($images->get() as $image)
			{
				$deleteId = $this->_mav->deleteImage."_".$image->ImageId();
				
				if($this->_pv->valueIsSet($deleteId) && $this->_pv->getValue($deleteId) == $image->ImageId())
					$imagesToDelete[] = $image->ImageId();
			}
		
			// Tar bort eventuella bilder
			if(count($imagesToDelete)>0)
			{
				if($this->_mam->deleteImages($imagesToDelete, $albumId))
					$this->_pv->updatePage(array($this->_pv->controller, $this->_pv->status, $this->_pv->albumId), 
					array($this->_pv->editAlbum, $this->_mav->imagesDeleted, $albumId));
				else
					$html .= $this->_pv->printErrors($this->_mam->errors);
			}
			// Uppdatera ej albumet om bilder ska tas bort
			else 
			{
				if($this->_mam->updateImages($updatedImages))
					$this->_pv->updatePage(array($this->_pv->controller, $this->_pv->status, $this->_pv->albumId), 
					array($this->_pv->editAlbum, $this->_mav->albumUpdated, $albumId));
				else
					$html .= $this->_pv->printErrors($this->_mam->errors);
			}
		}
		
		/********************************
		 * 	SKRIV UT STATUSMEDDELANDEN
		 * *****************************/
		
		if($this->_mav->albumUpdated())
			$html .= $this->_pv->setStatusText(\Common\Strings::DB_ALBUM_UPDATED, true);
		
		if($this->_mav->imagesDeleted())
			$html .= $this->_pv->setStatusText(\Common\Strings::DB_IMAGES_DELETE_SUCCESS, true);
		
		
		/********************************
		 * 		HÄMTA FORMULÄR
		 * *****************************/
		 
		// Hämta formulär för editering samt bilduppladdning
		$html .= $this->_mav->editAlbumForm($album);
		
		// Rubrik
		$html .= $this->_pv->encapsulateString("h2", \Common\Strings::HEADER_UPLOAD_IMAGE);
		
		
		// Formulär för att ladda upp bild
		$html .= $this->_pv->encapsulateString("em", \Common\Strings::TEXT_UPLOAD_INFO . (\Common\Settings::IMAGE_MAXSIZE / 1000000) . " MB");
		
		// Ladda upp bild och skriv ut statusmeddelande
		if($this->_pv->valueIsSet($this->_mav->tryUploadImage))
			$html .= $this->uploadImage($album->AlbumId());
		
		$html .= $this->_mav->addImageForm($albumId);
		
		// Hämta albumbilder
		$images = $this->_ic->getImages($this->_db, $album->AlbumId());
		
		// Rubrik
		$html .= $this->_pv->encapsulateString("h2", \Common\Strings::HEADER_EDIT_IMAGES);
		
		if($images != false)
		{
			$imagesHtml = $this->_mav->getImagesForms($images);
		 
			if($imagesHtml != false)
				$html .= $imagesHtml;
		}
		else
			$html .= $this->_pv->encapsulateString("p", \Common\Strings::DB_IMAGES_NOT_ADDED);
		
		return $html;
	}
	
	private function getAlbumPath($albumId)
	{
		return "uploads/albums/".$this->_lm->getUserName()."/album_".$albumId."/";
	}
	
	private function uploadImage($albumId)
	{
		$html = "";
		
		$fu = new \Models\FileUpload($this->getAlbumPath($albumId), \Common\Settings::IMAGE_MAXSIZE, $this->_mav->file);
		
		// Kollar så bilden är giltig
		if($fu->isValidImage($_FILES))
		{
			// Ladda upp bilden
			$imgUrl = $fu->uploadFile($_FILES);
			
			// Om uppladdningen lyckats
			if($imgUrl != false)
			{
				// Skapa tumnagel
				$thumbUrl = $fu->createThumb($imgUrl, 100);
				
				// Om tumnageln skapats
				if($thumbUrl != false)
				{
					//$html .= $this->_pv->setStatusText(\Common\Strings::UPLOAD_CREATE_THUMB_SUCCESS, true);
					
					$image = new \Models\Image(0, $albumId, "", $imgUrl, $thumbUrl);
					
					// Om det inte går att lägga till bild i DB (Returnerar 0 vid fel)
					if($this->_mam->addImage($image) == 0)
					{
						// Ta bort bild och thumb
						$thumbPath = ABSPATH . "/" . $thumbUrl;
						unlink($thumbPath);
						
						$html .= $this->_pv->printErrors($this->_mam->errors);
					}
					// Om bild laddats upp, tumnagel skapats och bilden lagrats i DB
					else
						$html .= $this->_pv->setStatusText(\Common\Strings::UPLOAD_IMAGE_SUCCESS, true);
				}
				// Om tumnagel inte kunde skapas
				else
				{
					$imagePath = ABSPATH . "/" . $imgUrl;
					unlink($imagePath);
					
					$html .= $this->_pv->setStatusText(\Common\Strings::UPLOAD_IMAGE_FAIL, false);
				}
			}
			// Om uppladdning misslyckades
			else
				$html .= $this->_pv->setStatusText(\Common\Strings::UPLOAD_IMAGE_FAIL, false);
		}
		else
			$html .= $this->_pv->setStatusText(\Common\Strings::UPLOAD_IMAGE_INVALID, false);
		
		return $html;
	}
}
?>